package com.adou.common.util;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;

public class XUtilCommon {

    private static final Logger logger = LoggerFactory.getLogger(XUtilCommon.class);

    public static JSONObject sendGet(String urlStr, String content, String encoding) {
        JSONObject Result = new JSONObject();
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr + "?" + content);
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
            connection.setConnectTimeout(4000);// 设置连接超时时间，单位毫秒
            connection.setReadTimeout(4000);// 设置读取数据超时时间，单位毫秒
            connection.setRequestMethod("GET");// 提交方法POST|GET
            connection.connect();// 打开连接端口
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line.trim());
            }
            reader.close();
            Result = JSON.parseObject(buffer.toString());
        } catch (IOException e) {
            logger.error("获取URL连接错误:" + e.toString());
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }
        return Result;
    }

    public static JSONObject sendPost(String urlStr, String content, String encoding) {
        JSONObject Result = new JSONObject();
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
            connection.setConnectTimeout(4000);// 设置连接超时时间，单位毫秒
            connection.setReadTimeout(4000);// 设置读取数据超时时间，单位毫秒
            connection.setDoOutput(true);// 是否打开输出流 true|false
            connection.setDoInput(true);// 是否打开输入流true|false
            connection.setRequestMethod("POST");// 提交方法POST|GET
            connection.setUseCaches(false);// 是否缓存true|false
            connection.connect();// 打开连接端口
            DataOutputStream out = new DataOutputStream(connection
                    .getOutputStream());// 打开输出流往对端服务器写数据
            out.writeBytes(content);// 写数据,也就是提交您的表单 name=xxx&pwd=xxx
            out.flush();// 刷新
            out.close();// 关闭输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line.trim());
            }
            reader.close();
            Result = JSON.parseObject(buffer.toString());
        } catch (IOException e) {
            logger.error("获取URL连接错误:" + e.toString());
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }
        return Result;
    }

    public static JSONObject sendPost(String urlStr, JSONObject json, String encoding) {
        JSONObject Result = new JSONObject();
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
            connection.setConnectTimeout(4000);// 设置连接超时时间，单位毫秒
            connection.setReadTimeout(4000);// 设置读取数据超时时间，单位毫秒
            connection.setDoOutput(true);// 是否打开输出流 true|false
            connection.setDoInput(true);// 是否打开输入流true|false
            connection.setUseCaches(false);// 是否缓存true|false
            connection.setRequestMethod("POST");// 提交方法POST|GET
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), encoding); // utf-8编码
            out.append(json.toString());
            System.out.println(json.toString());
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line.trim());
            }
            reader.close();
            Result = JSON.parseObject(buffer.toString());
        } catch (IOException e) {
            logger.error("获取URL连接错误:" + e.toString());
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }
        return Result;
    }

    public static String sendPostByStr(String urlStr, String content, String encoding) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
            connection.setConnectTimeout(4000);// 设置连接超时时间，单位毫秒
            connection.setReadTimeout(4000);// 设置读取数据超时时间，单位毫秒
            connection.setDoOutput(true);// 是否打开输出流 true|false
            connection.setDoInput(true);// 是否打开输入流true|false
            connection.setRequestMethod("POST");// 提交方法POST|GET
            connection.setUseCaches(false);// 是否缓存true|false
            connection.connect();// 打开连接端口
            DataOutputStream out = new DataOutputStream(connection
                    .getOutputStream());// 打开输出流往对端服务器写数据
            out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
            out.flush();// 刷新
            out.close();// 关闭输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            logger.error("获取IP连接错误:" + e.toString());
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }
        return null;
    }

    public static void setjsapi_ticket(String sTicket) {
        try {
            SAXReader reader = new SAXReader();
            File file = new File(UtilPath.getClassPath() + "/ticket.xml");
            Document document = reader.read(file);
            Element root = document.getRootElement();
            root.element("jsapi_ticket").setText(sTicket);
            root.element("jsapi_refresh_date").setText(DateUtil.getNow(DateUtil.FORMAT_LONG));
            XMLWriter output = new XMLWriter(new FileWriter(new File(UtilPath.getClassPath() + "/ticket.xml")));
            output.write(document);
            output.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        } catch (DocumentException ex) {
            java.util.logging.Logger.getLogger(XUtilCommon.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String getjsapi_ticket() {
        try {
            SAXReader reader = new SAXReader();
            File file = new File(UtilPath.getClassPath() + "/ticket.xml");
            Document document = reader.read(file);
            Element root = document.getRootElement();
            List<Element> childElements = root.elements();
            String jsapi_refresh_date = "";
            String sTicket = "";
            for (Element child : childElements) {
                switch (child.getName()) {
                    case "jsapi_ticket":
                        sTicket = child.getText();
                        break;
                    case "jsapi_refresh_date":
                        jsapi_refresh_date = child.getText();
                        break;
                }
            }
            if (!jsapi_refresh_date.equals("")) {
                SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FORMAT_LONG);
                Date refdate = DateUtil.getATimeToDate(DateUtil.parse(jsapi_refresh_date, DateUtil.FORMAT_LONG), Integer.parseInt(IConfig.get("DefaultTime")));
                Date nowdate = sdf.parse(DateUtil.getNow(DateUtil.FORMAT_LONG));
                boolean flag = refdate.before(nowdate);
                if (!flag) {
                    return sTicket;
                }
            }
        } catch (DocumentException | ParseException ex) {
            System.out.println(ex.toString());
        }
        return null;
    }

    public static void setnormal_token(String token) {
        try {
            SAXReader reader = new SAXReader();
            File file = new File(UtilPath.getClassPath() + "/ticket.xml");
            Document document = reader.read(file);
            Element root = document.getRootElement();
            root.element("normal_token").setText(token);
            root.element("token_refresh_date").setText(DateUtil.getNow(DateUtil.FORMAT_LONG));
            XMLWriter output = new XMLWriter(new FileWriter(new File(UtilPath.getClassPath() + "/ticket.xml")));
            output.write(document);
            output.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        } catch (DocumentException ex) {
            java.util.logging.Logger.getLogger(XUtilCommon.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String getnormal_token() {
        try {
            SAXReader reader = new SAXReader();
            File file = new File(UtilPath.getClassPath() + "/ticket.xml");
            Document document = reader.read(file);
            Element root = document.getRootElement();
            List<Element> childElements = root.elements();
            String token_refresh_date = "";
            String sToken = "";
            for (Element child : childElements) {
                switch (child.getName()) {
                    case "normal_token":
                        sToken = child.getText();
                        break;
                    case "token_refresh_date":
                        token_refresh_date = child.getText();
                        break;
                }
            }
            if (!token_refresh_date.equals("")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date refdate = DateUtil.getATimeToDate(DateUtil.parse(token_refresh_date, DateUtil.FORMAT_LONG), Integer.parseInt(IConfig.get("DefaultTime")));
                Date nowdate = sdf.parse(DateUtil.getNow(DateUtil.FORMAT_LONG));
                boolean flag = refdate.before(nowdate);
                if (!flag) {
                    return sToken;
                }
            }
        } catch (DocumentException | ParseException ex) {
            System.out.println(ex.toString());
        }
        return null;
    }

    public static Map<String, String> getapp_info(String appid, String type) {
        Map<String, String> map = new HashMap<>();
        try {
            SAXReader reader = new SAXReader();
            File file = new File(UtilPath.getClassPath() + "/update.xml");
            Document document = reader.read(file);
            Element root = document.getRootElement();
            List<Element> elements = root.elements();
            for (Element child : elements) {
                if (child.attributeValue("id").equals(appid) && child.element("type").getText().equals(type)) {
                    map.put("title", URLDecoder.decode(child.element("title").getText(),"utf-8"));
                    map.put("type", child.element("type").getText());
                    map.put("name", child.element("name").getText());
                    map.put("ico", child.element("ico").getText());
                    map.put("ver", child.element("ver").getText());
                    map.put("appid", child.attributeValue("id"));
                    break;
                }
            }
        } catch (DocumentException ex) {
            System.out.println(ex.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static List<Map<String, String>> getapp_list() {
        List<Map<String, String>> list = new ArrayList<>();
        try {
            SAXReader reader = new SAXReader();
            File file = new File(UtilPath.getClassPath() + "/update.xml");
            Document document = reader.read(file);
            Element root = document.getRootElement();
            List<Element> elements = root.elements();
            for (Element child : elements) {
                Map<String, String> map = new HashMap<>();
                map.put("title", URLDecoder.decode(child.element("title").getText(),"utf-8"));
                map.put("type", child.element("type").getText());
                map.put("name", child.element("name").getText());
                map.put("ico", child.element("ico").getText());
                map.put("ver", child.element("ver").getText());
                map.put("appid", child.attributeValue("id"));
                list.add(map);
            }
        } catch (DocumentException ex) {
            System.out.println(ex.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void removeapp_ver(String appid, String type) {
        try {
            SAXReader reader = new SAXReader();
            File file = new File(UtilPath.getClassPath() + "/update.xml");
            Document document = reader.read(file);
            Element root = document.getRootElement();
            List<Element> elements = root.elements();
            for (Element child : elements) {
                if (child.attributeValue("id").equals(appid) && child.element("type").getText().equals(type)) {
                    root.remove(child);
                    break;
                }
            }
            XMLWriter output = new XMLWriter(new FileWriter(new File(UtilPath.getClassPath() + "/update.xml")));
            output.write(document);
            output.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        } catch (DocumentException ex) {
            java.util.logging.Logger.getLogger(XUtilCommon.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void setapp_ver(String appid, String title, String type, String name, String ico, String ver) {
        try {
            SAXReader reader = new SAXReader();
            File file = new File(UtilPath.getClassPath() + "/update.xml");
            Document document = reader.read(file);
            Element root = document.getRootElement();
            List<Element> elements = root.elements();
            boolean bflag = true;
            for (Element child : elements) {
                if (child.attributeValue("id").equals(appid) && child.element("type").getText().equals(type)) {
                    child.element("title").setText(URLEncoder.encode(title,"utf-8"));
                    child.element("type").setText(type);
                    child.element("name").setText(name);
                    child.element("ico").setText(ico);
                    child.element("ver").setText(ver);
                    bflag = false;
                    break;
                }
            }
            if (bflag) {
                Element ele = root.addElement("app").addAttribute("id", appid);
                ele.addElement("title").addText(URLEncoder.encode(title,"utf-8"));
                ele.addElement("type").setText(type);
                ele.addElement("name").setText(name);
                ele.addElement("ico").setText(ico);
                ele.addElement("ver").addText(ver);
            }
            XMLWriter output = new XMLWriter(new FileWriter(new File(UtilPath.getClassPath() + "/update.xml")));
            output.write(document);
            output.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        } catch (DocumentException ex) {
            java.util.logging.Logger.getLogger(XUtilCommon.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
